﻿// Microsoft Public License (Ms-PL)
// nRoute v5 (http://nroute.codeplex.com)
// Modifié par So@t

using System.Windows;
using System.Windows.Interactivity;
using CPN.PJN.Silverlight.UI.Interactions.Interactivity;

namespace CPN.PJN.Silverlight.UI.Interactions.Triggers
{

    /// <summary>
    /// Represents a trigger that can match a value being equal to the given value.
    /// </summary>
    public class ValueMatchTrigger : TriggerBase<FrameworkElement>
    {
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(object), typeof(ValueMatchTrigger), 
            new PropertyMetadata(null, new PropertyChangedCallback(OnSourceChanged)));

        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(object), typeof(ValueMatchTrigger),
            new PropertyMetadata(null));

        #region Properties

        public object Source
        {
            get { return GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        //[TypeConverter(typeof(ConvertFromStringConverter))]
        public object Value
        {
            get { return GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

        public bool Negate { get; set; }

        #endregion

        #region Handlers

        static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((ValueMatchTrigger)d).CompareValue(e.NewValue);
        }

        void CompareValue(object sourceValue)
        {
            // we need to convert it so that the maching can be done
            var _matchValue = sourceValue != null ? ConverterHelper.ConvertToType(Value, sourceValue.GetType()) : null;
            var _result = object.Equals(_matchValue, sourceValue);
            if (Negate) _result = !_result;
            if (_result)
                base.InvokeActions(sourceValue);
        }

        #endregion

    }
}
